import 'package:flutter/material.dart';

import 'NinePatchFlutterView.dart';

class NinePatchWithText extends StatefulWidget {
  final String? url;
  final Widget child;
  final Widget? placeholder;

  const NinePatchWithText({
    super.key,
    required this.url,
    required this.child,
    this.placeholder,
  });

  @override
  State<NinePatchWithText> createState() => _NinePatchWithTextState();
}

class _NinePatchWithTextState extends State<NinePatchWithText> {
  final GlobalKey _widgetKey = GlobalKey();
  double? boxHeight;
  double? boxWidth;
  bool isLoaded = false;

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      getSize();
    });
  }

  getSize() {
    final renderBox =
        _widgetKey.currentContext?.findRenderObject() as RenderBox?;
    if (renderBox != null && mounted) {
      setState(() {
        boxHeight = renderBox.size.height;
        boxWidth = renderBox.size.width;
      });
    }
  }

  @override
  void didUpdateWidget(covariant NinePatchWithText oldWidget) {
    super.didUpdateWidget(oldWidget);
    getSize();
  }

  @override
  Widget build(BuildContext context) {
    final child = Container(
      key: _widgetKey,
      child: widget.child,
    );

    if (boxHeight == null) {
      // 还没测量好，先返回空壳
      return Container(
        child: child,
      );
    }

    return SizedBox(
      height: boxHeight!,
      width: boxWidth!,
      child: Stack(
        children: [
          if (widget.placeholder != null && !isLoaded) widget.placeholder!,
          NinePatchFlutterView(
            url: widget.url,
            onLoaded: () {
              setState(() {
                isLoaded = true;
              });
            },
          ),
          child,
        ],
      ),
    );
  }
}
